//
//  HomePageViewController.m
//  HYApp
//
//  Created by Jianbo Cai on 2020/7/28.
//  Copyright © 2020 Unidax. All rights reserved.
//

#import "HomePageViewController.h"
#import <JXCategoryTitleView.h>
#import <JXCategoryIndicatorLineView.h>
#import "HomePageListView.h"
#import "HomePageHeaderView.h"
#import "UserCenterView.h"
#import "HistoryMainViewController.h"
#import "ProfileTableViewController.h"
#import "HYNetHelper.h"
#import "SheetView.h"
#import "ChangeVerifyView.h"
#import "HYNetHelper.h"
#import "AppDelegate.h"
#import "HYApp-Swift.h"
#import "AWUserInfo.h"
#import "EditPhoneNumberTableViewController.h"
#import <JFBase/JFBase.h>


@interface HomePageViewController ()<JXCategoryViewDelegate, JXPagerViewDelegate>

@property (nonatomic, strong) HomePageHeaderView *headerView;
@property (nonatomic, strong) JXPagerView *pagingView;
@property (nonatomic, strong) JXCategoryTitleView *segmentControl;
@property (nonatomic, strong) UIView *customNavBar;
@property (nonatomic, strong) NSMutableArray *listViewArray;
@property (nonatomic, strong) WalletsEntity *walletsEntity;

@property (nonatomic, copy) NSString *emial;

@property (nonatomic, assign) BOOL isRequest;


@end

@implementation HomePageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, MAX(1020.0 / 1125 * SCREEN_WIDTH, 280))];
    [imageView setImage:[UIImage imageNamed:@"banner"]];
    [self.view addSubview:imageView];
    
    [self.view addSubview:self.pagingView];
    [self.view addSubview:self.customNavBar];
    [self request];
    WEAKSELF
    [[NSNotificationCenter defaultCenter] addObserverForName:AW_NETWORK_ERRORRESONE object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) {
        id dict = note.object;
        if ([dict isKindOfClass:[NSDictionary class]]) {
            NSDictionary * xx = (NSDictionary*)dict;
            NSString * statusCode = xx[@"statusCode"];
            if ([@"401" isEqualToString:statusCode]) {
                [weakSelf showLoginOutAlert];
            }
        }
    }];
}

-(void)showLoginOutAlert{
    WEAKSELF
    FZAlertController *alertController = [FZAlertController alertControllerWithTitleImage:[UIImage imageNamed:@"alert_icon_failed"] title:JFMainLocalizedString(@"login.timeOut") customView:nil message:nil];
    alertController.showCloseBtn = YES;
    alertController.messageAlignment = NSTextAlignmentCenter;
    
    FZAlertAction *action = [FZAlertAction actionWithTitle:JFMainLocalizedString(@"exchange.ok") style:UIAlertActionStyleDefault handler:^(FZAlertAction *action) {
        weakSelf.isRequest = NO;
        [HYNetHelper setLogined:NO];
        [weakSelf autoLogin];
    }];
    [alertController addAction:action];
    [self presentViewController:alertController animated:YES completion:nil];
}

-(void)request{
    [self requestData];
    [self requestCurrencies];
    [self requestUserInfo];
}

-(void)autoLogin{
        self.isRequest = YES;
        WEAKSELF
        if ([HYNetHelper isLogined]) {
            return;
        }
        A0WebAuth * webAuth = [[A0WebAuth alloc] init];
        [webAuth setScope:@"openid profile email"];
        [webAuth start:^(NSError * error, A0Credentials * data) {
            if (!error) {
                [HYNetHelper setAuthToken:data.idToken];
                [HYNetHelper setLogined:YES];
                AWDispatch_main_async_safe(^{
                  [SLRemindView showHUDAddedTo:weakSelf.view animated:YES];
                })
                
                [HYNetHelper auth0auth:data.accessToken appId:[HYNetHelper appid] tfaToken:@""  verifyType:@"2"  callBack:^(JFResultVo *resultVo) {
                    [SLRemindView hideHUDForView:weakSelf.view animated:YES];
                    if (resultVo.errorNo == 0) {
                        [HYNetHelper setAuthToken:resultVo.results[@"token"]];
                        [[NSNotificationCenter defaultCenter]postNotificationName:@"changeRoot" object:nil];
                    }else{
                        NSDictionary *dataDict = resultVo.results[@"data"];
                        NSArray * available2faMethods  = dataDict[@"message"][@"available2faMethods"];
                        if(available2faMethods && [available2faMethods isKindOfClass:[NSArray class]]){
                            if ([available2faMethods containsObject:@"sms"]) {//手机登录
                                [weakSelf showVyAlert:1 accessToken:data.accessToken];
                            }else{//google验证
                                [weakSelf showVyAlert:2 accessToken:data.accessToken];
                            }
                        }
                    }
                }];
            }else{
                weakSelf.isRequest = NO;
            }
        }];
}
-(void)showVyAlert:(NSInteger)type accessToken:(NSString*)accessToken{
    ChangeVerifyView *view = [[[NSBundle mainBundle] loadNibNamed:@"ChangeVerifyView" owner:nil options:nil] firstObject];
    view.frame = CGRectMake(0, 0, CUSTOMVIEW_WIDTH, 110);
    view.isLogin = YES;
    view.accessToken = accessToken;
    if (type == 1) {
        view.verificationType =  VerificationTypeWithOnlySMS;
    }else if (type == 2){
        view.verificationType =  VerificationTypeWithOnlyGA;
    }else{
         view.verificationType =  VerificationTypeWithALL;
    }
    WEAKSELF
    FZAlertController *vc = [FZAlertController alertControllerWithTitleImage:[UIImage imageNamed:@"Captcha_ico_b"] title:nil customView:view message:nil];
    vc.showCloseBtn = YES;
    FZAlertAction *action = [FZAlertAction actionWithTitle:JFMainLocalizedString(@"confirm") style:UIAlertActionStyleDefault handler:^(FZAlertAction *action) {
         NSString * token  = view.codeText.text;
        [SLRemindView showHUDAddedTo:weakSelf.view animated:YES];
        [HYNetHelper auth0auth:accessToken appId:[HYNetHelper appid] tfaToken:token  verifyType:view.verifyType  callBack:^(JFResultVo *resultVo) {
            [SLRemindView hideHUDForView:weakSelf.view animated:YES];
            if (resultVo.errorNo == 0) {
                [HYNetHelper setAuthToken:resultVo.results[@"token"]];
                [[NSNotificationCenter defaultCenter]postNotificationName:@"changeRoot" object:nil];
            }
        }];
    }];
    [vc addAction:action];
    [self presentViewController:vc animated:YES completion:nil];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    if ([JFStringHelper isEmpty:User().mobile]) {
        [self changePhoneVc];
    }
}
-(void)changePhoneVc{
    EditPhoneNumberTableViewController *vc = [[UIStoryboard storyboardWithName:@"User" bundle:nil]instantiateViewControllerWithIdentifier:@"EditPhoneNumberTableViewController"];;
     [self.navigationController pushViewController:vc animated:YES];
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    if (!self.isRequest) {
      [self autoLogin];
    }
  
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}


- (void)userCenterAction {
    UserCenterView *view = [[[NSBundle mainBundle] loadNibNamed:@"UserCenterView" owner:nil options:nil] firstObject];
    view.frame = self.view.bounds;
    view.iconImageView.image = [UIImage imageNamed:@"logo"];
    view.emailLab.text = self.emial;
    WEAKSELF
    view.functionAction = ^(NSInteger index) {
        [weakSelf userCenterFunctionAction:index];
    };
    [self.view addSubview:view];
}

- (void)userCenterFunctionAction:(NSInteger)functionCode {
    switch (functionCode) {
        case 1:
            {
                HistoryMainViewController *vc = [[HistoryMainViewController alloc]init];
                [self.navigationController pushViewController:vc animated:YES];
            }
            break;
        case 3:
            {
                ProfileTableViewController *vc = [[UIStoryboard storyboardWithName:@"User" bundle:nil]instantiateViewControllerWithIdentifier:@"ProfileTableViewController"];;
                [self.navigationController pushViewController:vc animated:YES];
            }
            break;
        case 4:
        {
            NSArray *array = @[@"English", @"简体中文", @"繁體中文"];
            SheetView *view = [[[NSBundle mainBundle] loadNibNamed:@"SheetView" owner:nil options:nil] firstObject];
            view.frame = self.navigationController.view.bounds;
            view.titleArray = array;
            view.selectAction = ^(NSInteger index) {
                NSArray *array = @[@"en", @"zh-Hans", @"zh-Hant"];
                [JFInternationalHelper changeLanguage:array[index]];
                [[NSNotificationCenter defaultCenter]postNotificationName:@"changeLanguage" object:nil];
            };
            [self.navigationController.view addSubview:view];
        }
            break;
        case 5:{
            WEAKSELF
            A0WebAuth * webAuth = [[A0WebAuth alloc] init];
            [webAuth clearSessionWithFederated:false callback:^(BOOL flag) {
                if (flag) {
                    AWDispatch_main_async_safe(^{
                        weakSelf.isRequest = NO;
                        [HYNetHelper setLogined:NO];
                        [HYNetHelper setAuthToken:@""];
                        [[NSNotificationCenter defaultCenter]postNotificationName:@"changeRoot" object:nil];
                    })
                }
            }];

        }
            break;
            
        default:
            break;
    }
}

- (void)serviceAction {
    
}

- (void)historyAction {
    HistoryMainViewController *vc = [[HistoryMainViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)requestUserInfo{
    WEAKSELF
    [HYNetHelper allUsers:^(JFResultVo *resultVo) {
        if (resultVo.errorNo == 0) {
            weakSelf.emial = resultVo.results[@"email"];
            [User() initWithDic:resultVo.results];
        }
    }];
}

- (void)requestData {
    WEAKSELF
    [HYNetHelper wallets:^(JFResultVo *resultVo) {
        if (!resultVo.errorNo) {
            weakSelf.walletsEntity = [WalletsEntity yy_modelWithDictionary:resultVo.results];
            weakSelf.headerView.walletsEntity = weakSelf.walletsEntity;
            for (HomePageListView *view in weakSelf.listViewArray) {
                view.walletsEntity = weakSelf.walletsEntity;
            }
        }
    }];
}

- (void)requestCurrencies {
    [HYNetHelper currencies:^(JFResultVo *resultVo) {
        if (!resultVo.errorNo) {
            Currencies().currencieList = [NSArray yy_modelArrayWithClass:[Currencie class] json:resultVo.results[@"data"]];
        }
    }];
}

#pragma mark - JXPagingViewDelegate
- (UIView *)tableHeaderViewInPagerView:(JXPagerView *)pagerView {
    return self.headerView;
}

- (NSUInteger)tableHeaderViewHeightInPagerView:(JXPagerView *)pagerView {
    return CGRectGetHeight(self.headerView.frame);
}

- (NSUInteger)heightForPinSectionHeaderInPagerView:(JXPagerView *)pagerView {
    return 55;
}

- (UIView *)viewForPinSectionHeaderInPagerView:(JXPagerView *)pagerView {
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.frame), 55)];
    view.backgroundColor = UIColorFromHex(0xF4F5F7);
    [view addSubview:self.segmentControl];
    
    return view;
}

- (NSInteger)numberOfListsInPagerView:(JXPagerView *)pagerView {
    return self.segmentControl.titles.count;
}

- (id<JXPagerViewListViewDelegate>)pagerView:(JXPagerView *)pagerView initListAtIndex:(NSInteger)index {
    return self.listViewArray[index];
}


- (HomePageHeaderView *)headerView {
    if (!_headerView) {
        _headerView = [[[NSBundle mainBundle] loadNibNamed:@"HomePageHeaderView" owner:nil options:nil] firstObject];
        _headerView.frame = CGRectMake(0, 0, CUSTOMVIEW_WIDTH, 110);
        WEAKSELF
        _headerView.displayAction = ^{
            [weakSelf.pagingView resizeTableHeaderViewHeightWithAnimatable:YES duration:0.2 curve:UIViewAnimationCurveEaseIn];
        };
//        _headerView.dataValueArray = @[@(5), @(10), @(15), @(20), @(25), @(30)];
    }
    return _headerView;
}

- (JXCategoryTitleView *)segmentControl {
    if (!_segmentControl) {
        _segmentControl = [[JXCategoryTitleView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.frame), 50)];
        _segmentControl.backgroundColor = [UIColor whiteColor];
//        _segmentControl.titles = @[@"Overview",@"Digital",@"Currencies"];
        _segmentControl.titles = @[JFMainLocalizedString(@"Overview"),JFMainLocalizedString(@"digital"),JFMainLocalizedString(@"currencies")];
        _segmentControl.titleColor = UIColorFromHex(0x555555);
        _segmentControl.delegate = self;
        _segmentControl.titleFont = [UIFont fontWithName:@"PingFangSC-Regular" size:16.f];
        _segmentControl.titleSelectedFont = [UIFont fontWithName:@"PingFangSC-Medium" size:16.f];
        _segmentControl.cellSpacing = 20.f;
        _segmentControl.contentEdgeInsetLeft = 25.f;
        _segmentControl.contentEdgeInsetRight = 25.f;

        JXCategoryIndicatorLineView *lineView = [[JXCategoryIndicatorLineView alloc] init];
        _segmentControl.titleSelectedColor = lineView.indicatorColor = UIColorFromHex(0x70896A);
        lineView.indicatorWidth = 40;
        _segmentControl.indicators = @[lineView];
    }
    return _segmentControl;
}

- (JXPagerView *)pagingView {
    if (!_pagingView) {
        _pagingView = [[JXPagerView alloc] initWithDelegate:self];
        _pagingView.mainTableView.backgroundColor = AWThemeColorForKey(@"Global.backgroundColor");
        _pagingView.mainTableView.bounces = NO;
        _pagingView.frame = CGRectMake(0, SafeAreaTopHeight, SCREEN_WIDTH, SCREEN_HEIGHT - SafeAreaTopHeight);
        self.segmentControl.contentScrollView = _pagingView.listContainerView.collectionView;
        _pagingView.isListHorizontalScrollEnabled = NO;
    }
    return _pagingView;
}

- (NSMutableArray *)listViewArray {
    if (!_listViewArray) {
        _listViewArray = [NSMutableArray arrayWithCapacity:3];
        for (int i = 0; i < 3; i++) {
            HomePageListView *listView = [[HomePageListView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, self.pagingView.bounds.size.height - 55) type:i];
            [_listViewArray addObject:listView];
        }
    }
    return _listViewArray;
}

- (UIView *)customNavBar {
    if (!_customNavBar) {
        _customNavBar = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), SafeAreaTopHeight)];
        _customNavBar.backgroundColor = [UIColor clearColor];
        
      
//       _titleLabel = [[UILabel alloc] init];
//        [_customNavBar addSubview:_titleLabel];
//        _titleLabel.textAlignment = NSTextAlignmentCenter;
//        _titleLabel.font = [UIFont systemFontOfSize:17];
//        _titleLabel.textColor = [UIColor colorWithHexString:@"#ffffff"];
//        _titleLabel.alpha = 0;
//        _titleLabel.backgroundColor = [UIColor clearColor];
//        _titleLabel.frame = CGRectMake(0,CGRectGetHeight(_customNavBar.frame) - 44, CGRectGetWidth(_customNavBar.frame), 44);
    

        // 为了方便截图分享，，把返回按钮等放self上
        UIButton *userButton = [UIButton buttonWithType:UIButtonTypeCustom];
        userButton.frame = CGRectMake(15, 6 + StatusBarHeight, 26, 22);
        [userButton setImage:[UIImage imageNamed:@"personal_center_iocn"] forState:UIControlStateNormal];
        [userButton addTarget:self action:@selector(userCenterAction) forControlEvents:UIControlEventTouchUpInside];
        [_customNavBar addSubview:userButton];
        
        
        UIButton *serviceButton = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 41, 6 + StatusBarHeight, 26, 22)];
        [serviceButton addTarget:self action:@selector(serviceAction) forControlEvents:UIControlEventTouchUpInside];
        [serviceButton setImage:[UIImage imageNamed:@"lianxi"] forState:UIControlStateNormal];
        [_customNavBar addSubview:serviceButton];
        
        UIButton *historyButton = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 82, 6 + StatusBarHeight, 22, 22)];
        [historyButton addTarget:self action:@selector(historyAction) forControlEvents:UIControlEventTouchUpInside];
        [historyButton setImage:[UIImage imageNamed:@"lisjil"] forState:UIControlStateNormal];
        [_customNavBar addSubview:historyButton];
    }
    return _customNavBar;
}


@end
